//
//  APPLETextView.swift
//  123
//
//  Created by pangjiaxing on 16/1/8.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit

@IBDesignable class APPLETextView: UITextView {
    
    private lazy var placeholderLabel:UILabel = {
        let label=UILabel()
        label.text = "请输入文字"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines=0
        return label
    }()
    
    override var font : UIFont?{
        didSet{
            placeholderLabel.font=font
        }
    }
    
    override var text : String? {
        didSet{
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    @IBInspectable  var  placeholder : String?{
        didSet{
            placeholderLabel.text = text
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChange", name: UITextViewTextDidChangeNotification, object: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func textViewTextDidChange(){
        placeholderLabel.hidden = self.hasText()
    }
    
    private func setUpUI(){
        addSubview(placeholderLabel)
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        placeholderLabel.frame.size = (placeholderLabel.text!as NSString).boundingRectWithSize(CGSize(width: self.frame.width-2*self.placeholderLabel.frame.origin.x, height: CGFloat(MAXFLOAT)), options: [NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName:placeholderLabel.font], context: nil).size
        
    }
    
    
}
